package com.heba.greenmulu.user;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.article.ItemArticleObject;
import com.heba.config.CommonConfig;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.ItemArticleDetailActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.GlideUtil;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户收藏文章页面
 * <p>
 * Created by jason on 2019/2/12.
 */

public class UserArticleActivity extends BaseActivity {

    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<ItemArticleObject> itemArticleObjects = new ArrayList<>();
    private TextView alertLB;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recyclerview);
        initTopbar();
        findViewById();
        initView();
        getArticleData();
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        alertLB = findViewById(R.id.alertLB);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        alertLB.setText(R.string.no_fav_Article);
        txt_title.setText(getResources().getString(R.string.my_articles_s));
        recycleAdapter = new QuickAdapter<ItemArticleObject>(itemArticleObjects) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_user_article;
            }

            @Override
            public void convert(VH holder, final ItemArticleObject data, int position) {
                GlideUtil.loadImageWithDefaultPlaceHolder(UserArticleActivity.this, data.getImageUrl(), holder.getView(R.id.img_photo));
                holder.setText(R.id.txt_article, data.getTitle());
                holder.setText(R.id.txt_name, data.getPublisher());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString(CommonConfig.ARTICLE_ID, data.getArticleID());
                        openActivity(ItemArticleDetailActivity.class, bundle);
                    }
                });
            }
        };

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
        //设置分隔线
//        recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        //设置增加或删除条目的动画
//        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                Page = 1;
                isRefreshFromTop = true;
                getArticleData();
            }
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                Page++;
                isRefreshFromTop = false;
                getArticleData();
            }
        });
    }

    /**
     * 获取收藏文章
     */
    private void getArticleData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Article/CollectList", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();

                        /**
                         * 判断是否需要清除数据
                         */
                        if (isRefreshFromTop) {
                            if (!itemArticleObjects.isEmpty()) {

                                itemArticleObjects.clear();
                            }
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }

                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateArticleData(array);
                                alertLB.setVisibility(View.GONE);
                            } else {
                                recycleAdapter.notifyDataSetChanged();
                                ToastShow.displayToast(UserArticleActivity.this, getResources().getString(R.string.finish_no_data));
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                alertLB.setVisibility(View.VISIBLE);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        if (isRefreshFromTop) {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }
                    }

                });
    }

    /**
     * updateArticleData
     *
     * @param data
     */
    private void updateArticleData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemArticleObject articleObject = new ItemArticleObject();
                articleObject.setArticleID(object.getString("ArticleID"));
                articleObject.setTitle(object.getString("Title"));
                articleObject.setPublisher(object.getString("Publisher"));
                articleObject.setImageUrl(object.getString("ImageUrl"));
                itemArticleObjects.add(articleObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新数据
        recycleAdapter.notifyDataSetChanged();

    }
}
